<template>
  <initVanta 
    :color="vantaData.hexToNumber(selectedColor)" 
    :effect="selectedEffect"
    ref="vantaBg"
  />
  <div>
    <div class="content-overlay">
      <div class="header">
        <backButton />
      </div>
      <div class="title">
        <h1>Settings</h1>
      </div>
      <div class="main-content">
        <div class="settings-container">
          <!-- 用户信息设置区域 -->
          <div class="setting-section">
            <h2>用户信息</h2>
            <div class="user-info-form">
              <div class="form-group">
                <label>Email</label>
                <input v-model="settings.email" class="form-control" placeholder="请输入邮箱地址" type="email">
              </div>
              <div class="form-group">
                <label>Location</label>
                <input v-model="settings.site" class="form-control" placeholder="请输入所在Site,如SH HL">
              </div>
            </div>
            <div class="button-group">
              <button class="save-btn" @click="saveSettings">Save</button>
              <button class="clear-btn" @click="clearAndSave">Clear</button>
            </div>
          </div>

          <!-- 控制台监控区域 -->
          <div class="setting-section">
            <h2>控制台监控</h2>
            <div class="console-monitor">
              <div class="console-controls">
                <div class="control-group">
                  <button 
                    class="control-btn" 
                    :class="{ active: isMonitoring }" 
                    @click="toggleMonitoring"
                  >
                    {{ isMonitoring ? '停止监控' : '开始监控' }}
                  </button>
                  <button class="control-btn" @click="clearLogs">清空日志</button>
                  <button class="control-btn" @click="exportLogs">导出日志</button>
                </div>
                <div class="filter-group">
                  <select v-model="logFilter" class="filter-select">
                    <option value="all">所有日志</option>
                    <option value="log">普通日志</option>
                    <option value="warn">警告</option>
                    <option value="error">错误</option>
                    <option value="info">信息</option>
                  </select>
                  <label class="auto-scroll-label">
                    <input type="checkbox" v-model="autoScroll" />
                    自动滚动
                  </label>
                </div>
              </div>
              
              <div class="console-display" ref="consoleDisplay">
                <div 
                  v-for="(log, index) in filteredLogs" 
                  :key="index" 
                  class="log-entry" 
                  :class="`log-${log.level}`"
                >
                  <span class="log-timestamp">{{ formatTimestamp(log.timestamp) }}</span>
                  <span class="log-level">{{ log.level.toUpperCase() }}</span>
                  <span class="log-message">{{ formatLogMessage(log.message) }}</span>
                </div>
                <div v-if="filteredLogs.length === 0" class="no-logs">
                  暂无日志数据
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue';
import backButton from '../components/backButton.vue';
import initVanta from '../components/initVanta.vue';
import { ElMessage } from 'element-plus';
import { useVanta } from '../components/useVanta';

const { selectedColor, selectedEffect, hexToNumber } = useVanta();

const vantaData = useVanta();

declare const electronAPI: any;
declare const consoleAPI: any;

// 控制台监控相关的类型定义
interface LogEntry {
  timestamp: number;
  level: 'log' | 'warn' | 'error' | 'info';
  message: string | object;
}

// 定义设置项类型
interface Settings {
  theme: string;
  notificationsEnabled: boolean;
  language: string;
  developerMode: boolean;
  name: string;
  email: string;    
  site: string;       
}

const settings = reactive<Settings>({
  theme: localStorage.getItem('theme') || 'light',
  notificationsEnabled: localStorage.getItem('notifications') === 'true',
  language: localStorage.getItem('language') || 'zh-CN',
  developerMode: false,
  name: localStorage.getItem('user_name') || '',   
  email: localStorage.getItem('user_email') || '',
  site: localStorage.getItem('user_site') || ''
});

// 控制台监控相关的响应式数据
const logs = ref<LogEntry[]>([]);
const isMonitoring = ref(false);
const logFilter = ref<'all' | 'log' | 'warn' | 'error' | 'info'>('all');
const autoScroll = ref(true);
const consoleDisplay = ref<HTMLElement>();

// 过滤后的日志
const filteredLogs = computed(() => {
  if (logFilter.value === 'all') {
    return logs.value;
  }
  return logs.value.filter(log => log.level === logFilter.value);
});

// electron-store数据文件路径
// %APPDATA%\automation-tools-platform\config.json

const saveSettings = async () => {
  if (!settings.email || !/^[\w.-]+@[\w.-]+\.\w+$/.test(settings.email)) {
    ElMessage.error('Please enter a valid email address.');
    return;
  }
  if (!settings.site.trim()) {
    ElMessage.error('Please enter your site.');
    return;
  }
  try {
    localStorage.setItem('user_name', settings.name);
    localStorage.setItem('user_email', settings.email);
    localStorage.setItem('user_site', settings.site);
    await electronAPI.saveSettings({
      name: settings.name,
      email: settings.email,
      site: settings.site
    });
    ElMessage.success('设置保存成功');
  } catch (error) {
    console.error('保存设置失败:', error);
    ElMessage.error('保存设置失败');
  }
};

const clearAndSave = async () => {
  settings.name = '';
  settings.email = '';
  settings.site = '';
  try {
    localStorage.setItem('user_name', '');
    localStorage.setItem('user_email', '');
    localStorage.setItem('user_site', '');
    await electronAPI.saveSettings({
      name: '',
      email: '',
      site: ''
    });
    ElMessage.success('数据已清空');
  } catch (error) {
    console.error('清空数据失败:', error);
    ElMessage.error('清空数据失败');
  }
};

// 控制台监控相关方法
const formatTimestamp = (timestamp: number): string => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    fractionalSecondDigits: 3
  });
};

const formatLogMessage = (message: string | object): string => {
  if (typeof message === 'string') {
    return message;
  }
  
  if (typeof message === 'object' && message !== null) {
    try {
      return JSON.stringify(message, null, 2);
    } catch (error: any) {
      return `[无法解析的对象: ${error.message}]`;
    }
  }
  
  return String(message);
};

const scrollToBottom = async () => {
  if (autoScroll.value && consoleDisplay.value) {
    await nextTick();
    consoleDisplay.value.scrollTop = consoleDisplay.value.scrollHeight;
  }
};

const addLogEntry = (logEntry: LogEntry) => {
  logs.value.push(logEntry);
  // 限制日志数量，避免内存溢出
  if (logs.value.length > 1000) {
    logs.value = logs.value.slice(-800);
  }
  scrollToBottom();
};

const toggleMonitoring = async () => {
  try {
    if (isMonitoring.value) {
      await consoleAPI.stopConsoleMonitoring();
      isMonitoring.value = false;
      ElMessage.success('控制台监控已停止');
    } else {
      await consoleAPI.startConsoleMonitoring();
      isMonitoring.value = true;
      ElMessage.success('控制台监控已开始');
    }
  } catch (error) {
    console.error('切换监控状态失败:', error);
    ElMessage.error('操作失败');
  }
};

const clearLogs = async () => {
  try {
    await consoleAPI.clearConsoleLogs();
    logs.value = [];
    ElMessage.success('日志已清空');
  } catch (error) {
    console.error('清空日志失败:', error);
    ElMessage.error('清空日志失败');
  }
};

const exportLogs = () => {
  try {
    const logText = filteredLogs.value
      .map(log => `[${formatTimestamp(log.timestamp)}] ${log.level.toUpperCase()}: ${formatLogMessage(log.message)}`)
      .join('\n');
    
    const blob = new Blob([logText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `console-logs-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    ElMessage.success('日志已导出');
  } catch (error) {
    console.error('导出日志失败:', error);
    ElMessage.error('导出日志失败');
  }
};

// 生命周期钩子
onMounted(async () => {
  try {
    // 获取历史日志
    const historyLogs = await consoleAPI.getConsoleLogs();
    // console.log('获取到的历史日志:', historyLogs);
    
    // 转换历史日志格式
    if (historyLogs && Array.isArray(historyLogs)) {
      logs.value = historyLogs.map((logEntry: any) => ({
        timestamp: logEntry.timestamp || Date.now(),
        level: logEntry.level || 'info',
        message: logEntry.message || logEntry
      }));
    } else {
      logs.value = [];
    }
    
    // 监听实时日志
    consoleAPI.onConsoleLog((logEntry: any) => {
      // console.log('onConsoleLog 接收到的数据:', logEntry);
      // 转换数据格式以匹配LogEntry接口
      const formattedEntry: LogEntry = {
        timestamp: logEntry.timestamp || Date.now(),
        level: logEntry.level || 'info',
        message: logEntry.message || logEntry
      };
      addLogEntry(formattedEntry);
    });
    
    // 监听批量日志
    consoleAPI.onConsoleLogsBatch((logEntries: any[]) => {
      console.log('onConsoleLogsBatch 接收到的数据:', logEntries);
      logEntries.forEach(logEntry => {
        const formattedEntry: LogEntry = {
          timestamp: logEntry.timestamp || Date.now(),
          level: logEntry.level || 'info',
          message: logEntry.message || logEntry
        };
        addLogEntry(formattedEntry);
      });
    });
    
    // 监听日志清空事件
    consoleAPI.onConsoleCleared(() => {
      logs.value = [];
    });
    
    scrollToBottom();
  } catch (error) {
    console.error('初始化控制台监控失败:', error);
  }
});

onUnmounted(() => {
  // 清理事件监听器
  if (consoleAPI && consoleAPI.removeConsoleLogListeners) {
    consoleAPI.removeConsoleLogListeners();
  }
});

</script>

<style scoped>
.content-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  padding: 20px;
}

.title {
  position: fixed;
  top: 80px;
  left: 0;
  right: 0;
  z-index: 999;
  padding: 20px;
}

.title h1 {
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  height: calc(100vh - 140px);
  margin-top: 140px;
  padding-top: 20px;
  mask-image: linear-gradient(to bottom, transparent 0%, black 20px, black calc(100% - 20px), transparent 100%);
  -webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 20px, black calc(100% - 20px), transparent 100%);
}

.main-content::-webkit-scrollbar {
  width: 8px;
}

.main-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.main-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.main-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

.settings-container {
  padding: 0 20px 20px 20px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.setting-section {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 1.5rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.setting-section h2 {
  color: #fff;
  margin: 0 0 1rem 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.user-info-form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.form-group input {
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.3);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #4285F4;
}

.button-group {
  display: flex;
  gap: 10px;
}

.save-btn {
  background: #4285F4;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s;
}

.save-btn:hover {
  background: #357ABD;
}

.clear-btn {
  background: #dc3545;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s;
}

.clear-btn:hover {
  background: #bb2d3b;
}

/* 控制台监控样式 */
.console-monitor {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  padding: 1rem;
}

.console-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.control-group {
  display: flex;
  gap: 0.5rem;
}

.control-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.control-btn.active {
  background: #28a745;
  border-color: #28a745;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.filter-select {
  padding: 6px 12px;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(0, 0, 0, 0.3);
  color: #fff;
  font-size: 14px;
}

.auto-scroll-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.console-display {
  height: 400px;
  overflow-y: auto;
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  padding: 1rem;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  text-align: left;
}

.log-entry {
  display: flex;
  margin-bottom: 4px;
  padding: 2px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  text-align: left;
}

.log-timestamp {
  color: #888;
  margin-right: 8px;
  min-width: 80px;
  font-size: 11px;
}

.log-level {
  margin-right: 8px;
  min-width: 50px;
  font-weight: bold;
  font-size: 11px;
}

.log-message {
  flex: 1;
  word-break: break-word;
  white-space: pre-wrap;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}

.log-log {
  color: #fff;
}

.log-log .log-level {
  color: #17a2b8;
}

.log-warn {
  color: #ffc107;
}

.log-warn .log-level {
  color: #ffc107;
}

.log-error {
  color: #dc3545;
}

.log-error .log-level {
  color: #dc3545;
}

.log-info {
  color: #28a745;
}

.log-info .log-level {
  color: #28a745;
}

.no-logs {
  text-align: center;
  color: #888;
  font-style: italic;
  padding: 2rem;
}

/* 滚动条样式 */
.console-display::-webkit-scrollbar {
  width: 8px;
}

.console-display::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.console-display::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.console-display::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-container {
    padding: 1rem;
  }
  
  .user-info-form {
    grid-template-columns: 1fr;
  }
  
  .console-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .control-group {
    justify-content: center;
  }
  
  .filter-group {
    justify-content: center;
  }
}
</style>